
String.prototype.format = function (dict) {
    return this.replace(/\{(\w+)\}/g, function (s, i) {
        return dict[i];
    });
};

let prew_ = '<li class="page-item"> \
                        <a class="page-link" href="#" aria-label="Previous">  \
                          <span aria-hidden="true">&laquo;</span> \
                          <span class="sr-only">Previous</span> \
                        </a> \
                      </li>'

let next_ = '<li class="page-item"> \
                        <a class="page-link" href="#" aria-label="Next">  \
                          <span aria-hidden="true">&raquo;</span> \
                          <span class="sr-only">Next</span> \
                        </a> \
                      </li>'

let pagestr = '<li class="page-item"><a class="page-link" href="#">{page}</a></li>'
let curpagestr = '<li class="page-item active"><a class="page-link" href="#">{page}</a></li>'
let invalidpagestr = '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>'

function ResetPage(total_page, cur_page) {

    curpagestr = curpagestr.format({ 'page': cur_page })
    let totalstr = ""
    //以当前页为分割，处理前边的标签页
    if (cur_page <= 1) {
        console.log("this is page one")
        totalstr += curpagestr
    } else if (cur_page <= 3) {
        totalstr = prew_
        let index = 1
        while (index < cur_page) {
            let one_page = pagestr.format({ 'page': index })
            totalstr += one_page
            index++
        }

        totalstr += curpagestr
    } else if (cur_page) {
        totalstr = prew_
        let index = cur_page - 1
        let page_1 = pagestr.format({ 'page': 1 })
        totalstr += page_1
        totalstr += invalidpagestr
        let page_pre = pagestr.format({ 'page': index })
        totalstr += page_pre
        totalstr += curpagestr
    }

    //以当前页为分割，处理后边的分页
    if (cur_page >= total_page) {
        return totalstr;
    }

    if (cur_page <= total_page - 3) {
        let page_next = pagestr.format({ 'page': cur_page + 1 })
        totalstr += page_next
        totalstr += invalidpagestr
        let page_end = pagestr.format({ 'page': total_page })
        totalstr += page_end
        totalstr += next_
        return totalstr;
    }

    if (cur_page < total_page) {
        let index = cur_page + 1
        while (index <= total_page) {
            let page_one = pagestr.format({ 'page': index })
            totalstr += page_one
            index++
        }

        totalstr += next_
        return totalstr;
    }
    return totalstr;
}

//请求文章列表
function GetArticleList(curpage) {
    post_data = {
        "curpage": curpage
    }

    $.ajax(
        {
            type: "post",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(post_data),
            url: "/article-list",
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.errorcode != 0) {
                    alert(`request error , code is ${data.errorcode}`)
                    return;
                }

                //编译模板的里的内容
                var template = Handlebars.compile($('#template-article-list').html());
                //把后台获取到的数据student渲染到页面
                $('#article-list-div').html(template(data.article_list));

                console.log('data is', data)
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // 状态码
                console.log(XMLHttpRequest.status);
                // 状态
                console.log(XMLHttpRequest.readyState);
                // 错误信息   
                console.log(textStatus);
            }
        }
    )
}

//请求单个文章的详情
function GetArticleDetail(article_id) {
    let post_data = { 'article_id': article_id }
    $.ajax(
        {
            type: "post",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(post_data),
            url: "/article-detail",
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.errorcode != 0) {
                    alert(`request error , code is ${data.errorcode}`)
                    return;
                }
                console.log("get article deatail is ", data)
                //编译模板的里的内容
                var template = Handlebars.compile($('#template-article-info').html());
                //把后台获取到的数据student渲染到页面
                $('#article-info-div').html(template(data['article-detail']));
                $('#article-title-div>h1').html(data['article-detail'].title);
                $('.article-div').html(data['article-detail']['html-content'])
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // 状态码
                console.log(XMLHttpRequest.status);
                // 状态
                console.log(XMLHttpRequest.readyState);
                // 错误信息   
                console.log(textStatus);
            }
        }
    )
}

//请求单个文章编辑页面内容

function GetArticleEdit(article_id) {
    let post_data = { 'article_id': article_id }
    $.ajax(
        {
            type: "post",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(post_data),
            url: "/article-detail",
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.errorcode != 0) {
                    alert(`request error , code is ${data.errorcode}`)
                    return;
                }
                console.log("get article deatail is ", data)
                $("textarea.editormd-markdown-textarea").text(data['article-detail']['md-content'])
                $("#title-input").val(data['article-detail']['title'])
                $("#title-input").attr('data-artid', data['article-detail']['artid'])
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // 状态码
                console.log(XMLHttpRequest.status);
                // 状态
                console.log(XMLHttpRequest.readyState);
                // 错误信息   
                console.log(textStatus);
            }
        }
    )
}

//请求发布文章页面
$('#publish-btn').click(function () {

    window.location.href = '/publish'

});

//发送发布文章的内容
$("#publish-post-btn").click(function () {
    console.log("publish-btn clicked")
    var title = $('#title-input').val()
    if (title == "") {
        alert("article title is empty !!!")
        return
    }
    //获取md内容转化为html
    var testView = editormd.markdownToHTML("test-markdown-view", {
        markdown: $("textarea.editormd-markdown-textarea").text(),
    });

    //组装json发送给服务器
    let post_data = {
        "md-content": $("textarea.editormd-markdown-textarea").text(),
        "html-content": $("#test-markdown-view").prop("outerHTML"),
        "title": title,
    }

    $.ajax({
        type: "post",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(post_data),
        url: "/publish-article",
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.errorcode != 0) {
                alert(`request error , code is ${data.errorcode}`)
                return;
            }

            window.location.href = '/'
        },

        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // 状态码
            console.log(XMLHttpRequest.status);
            // 状态
            console.log(XMLHttpRequest.readyState);
            // 错误信息   
            console.log(textStatus);
        }
    });
});

//编辑界面更新文章内容按钮点击事件
$("#publish-edit-btn").click(function () {
    console.log("publish-edit-btn clicked")
    var title = $('#title-input').val()
    var artid = $('#title-input').attr('data-artid')
    console.log('art id is ', artid)
    if (title == "") {
        alert("article title is empty !!!")
        return
    }
    //获取md内容转化为html
    var testView = editormd.markdownToHTML("test-markdown-view", {
        markdown: $("textarea.editormd-markdown-textarea").text(),
    });

    //组装json发送给服务器
    let post_data = {
        "md-content": $("textarea.editormd-markdown-textarea").text(),
        "html-content": $("#test-markdown-view").prop("outerHTML"),
        "title": title,
        "artid": artid,
    }

    $.ajax({
        type: "post",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(post_data),
        url: "/update-article",
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.errorcode != 0) {
                alert(`request error , code is ${data.errorcode}`)
                return;
            }

            window.location.href = '/'
        },

        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // 状态码
            console.log(XMLHttpRequest.status);
            // 状态
            console.log(XMLHttpRequest.readyState);
            // 错误信息   
            console.log(textStatus);
        }
    });
})

//编辑页面点击返回列表
$('#return-index-btn').click(function () {
    window.location.href = '/'
})


//点击删除文章响应逻辑
$('#article-list-div').on('click', 'a.article-del', (event) => {
    console.log("delete article clicked, artid is ", $(event.target).attr("data-artid"))
    var post_data = {
       "artid" :$(event.target).attr("data-artid"),
    }
    $.ajax(
        {
            type: "post",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(post_data),
            url: "/delete-article",
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.errorcode != 0) {
                    alert(`request error , code is ${data.errorcode}`)
                    return;
                }

                window.location.href = '/'
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // 状态码
                console.log(XMLHttpRequest.status);
                // 状态
                console.log(XMLHttpRequest.readyState);
                // 错误信息   
                console.log(textStatus);
            }
        });
})


